<template>
  <div id="app">
    <AppHeader v-if="showHeader" />
    <el-container>
      <el-aside width="200px" v-if="showHeader">
        <el-menu
          :router="true"
          :default-active="$route.path"
          class="el-menu-vertical"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
        >
          <el-menu-item index="/dashboard">
            <el-icon><DataLine /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="/graph-analysis" v-if="hasPermission('graph:view') || hasAnyAnalysisPermission">
            <el-icon><Share /></el-icon>
            <span>知识图谱分析</span>
          </el-menu-item>
          <el-menu-item index="/user-management" v-if="hasPermission('user:manage')">
            <el-icon><User /></el-icon>
            <span>用户权限管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-main>
          <Suspense>
            <template #default>
              <router-view />
            </template>
            <template #fallback>
              <div class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>
            </template>
          </Suspense>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import AppHeader from '@/components/AppHeader.vue';
import { DataLine, Share, User } from '@element-plus/icons-vue'
import { hasPermission } from '@/utils/permission';
import NProgress from 'nprogress';
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

export default {
  name: 'App',
  components: {
    AppHeader,
    DataLine,
    Share,
    User,
    ElConfigProvider
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const graphMenuItem = ref(null);
    
    // 使用ref控制菜单显示
    const showGraphMenu = ref(false);
    
    // 在登录页面和注册页面不显示头部和侧边栏
    const showHeader = computed(() => {
      const currentRoute = route.path;
      // 在登录和注册页面不显示
      if (currentRoute === '/login' || currentRoute === '/register') {
        return false;
      }
      
      // 检查用户登录状态
      const hasToken = store.getters.token;
      const hasUserInfo = store.getters.userInfo;
      
      console.log('[App] 检查显示头部状态:', {
        路由: currentRoute,
        Token: hasToken,
        用户信息: hasUserInfo
      });
      
      return hasToken && hasUserInfo;
    });
    
    // 检查是否有任何图谱分析权限
    const hasAnyGraphPermission = computed(() => {
      try {
        console.log('[App] 检查图谱分析权限...');
        if (!store.state.user || !store.getters.permissions) {
          console.log('[App] 用户状态或权限未初始化');
          return false;
        }
        
        console.log('[App] 当前用户权限列表:', store.getters.permissions);
        
        // 检查graph:view权限
        const hasGraphView = store.getters.permissions.includes('graph:view');
        console.log('[App] 用户是否有graph:view权限:', hasGraphView);
        
        // 检查analysis权限
        const analysisPermissions = store.getters.permissions.filter(p => p.startsWith('analysis:'));
        console.log('[App] 用户分析类权限:', analysisPermissions);
        
        const result = store.getters.hasAnyGraphPermission;
        console.log('[App] 最终判断结果:', result);
        return result;
      } catch (error) {
        console.error('[App] 检查图谱分析权限失败:', error);
        return false;
      }
    });
    
    // 检查是否有任何analysis开头的权限
    const hasAnyAnalysisPermission = computed(() => {
      return hasPermission('analysis:supply-chain') ||
             hasPermission('analysis:industry-chain') ||
             hasPermission('analysis:company-risk') ||
             hasPermission('analysis:high-tech') ||
             hasPermission('analysis:product-chain') ||
             hasPermission('analysis:company-stats');
    });
    
    // 检查当前用户是否为admin
    const isAdminUser = computed(() => {
      try {
        const userInfo = store.getters.userInfo;
        if (!userInfo) {
          console.log('[App] 用户信息未加载，不检查admin身份');
          return false;
        }
        
        console.log('[App] 当前用户名:', userInfo.username);
        const isAdmin = userInfo.username === 'admin';
        console.log('[App] 是否为admin用户:', isAdmin);
        return isAdmin;
      } catch (error) {
        console.error('[App] 检查admin身份失败:', error);
        return false;
      }
    });
    
    // 手动检查用户权限并控制菜单显示
    const checkAndShowGraphMenu = () => {
      console.log('[App] 手动检查知识图谱菜单权限...');
      const permissions = store.getters.permissions;
      console.log('[App] 权限列表:', permissions);
      
      if (!permissions || !Array.isArray(permissions)) {
        console.log('[App] 权限列表无效');
        return;
      }
      
      // 直接检查权限
      const hasGraphView = permissions.includes('graph:view');
      const hasAnalysis = permissions.some(p => p && typeof p === 'string' && p.startsWith('analysis:'));
      
      console.log('[App] 手动检查 - graph:view权限:', hasGraphView);
      console.log('[App] 手动检查 - 分析类权限:', hasAnalysis);
      
      if (hasGraphView || hasAnalysis) {
        console.log('[App] 用户有知识图谱相关权限，显示菜单...');
        showGraphMenu.value = true;
      } else {
        console.log('[App] 用户无知识图谱相关权限，隐藏菜单');
        showGraphMenu.value = false;
      }
    };
    
    // 监听权限变化
    watch(() => store.getters.permissions, (newPermissions) => {
      console.log('[App] 检测到权限变化:', newPermissions);
      checkAndShowGraphMenu();
    }, { deep: true });
    
    // 监听路由变化，确保用户信息已加载
    watch(() => route.path, async (newPath) => {
      if (newPath !== '/login' && newPath !== '/register') {
        const token = store.getters.token;
        const userInfo = store.getters.userInfo;
        
        console.log('[App] 路由变化，检查用户信息:', {
          路由: newPath,
          Token存在: !!token,
          用户信息存在: !!userInfo
        });
        
        // 如果有token但没有用户信息，尝试重新获取
        if (token && !userInfo) {
          console.log('[App] 检测到token但无用户信息，尝试获取用户信息');
          try {
            await store.dispatch('getUserInfo');
            console.log('[App] 用户信息获取成功');
          } catch (error) {
            console.error('[App] 获取用户信息失败:', error);
          }
        }
      }
    }, { immediate: true });
    
    // 页面加载时打印当前权限
    onMounted(() => {
      console.log('[App] 应用初始化...');
      
      // 确保关闭任何残留的进度条
      setTimeout(() => {
        NProgress.done();
        // 额外检查并移除DOM上的进度条元素
        const nprogressElement = document.querySelector('#nprogress');
        if (nprogressElement) {
          console.log('[App] 发现残留的进度条DOM，手动移除');
          nprogressElement.remove();
        }
      }, 300);
      
      // 记录初始状态
      const initialUserInfo = store.getters.userInfo;
      const initialPermissions = store.getters.permissions;
      console.log('[App] 初始用户信息:', initialUserInfo);
      console.log('[App] 初始权限列表:', initialPermissions);
      console.log('[App] 初始权限类型:', typeof initialPermissions);
      console.log('[App] 初始时是否显示知识图谱菜单:', hasAnyGraphPermission.value);
      
      // 初次检查
      checkAndShowGraphMenu();
      
      // 如果用户已登录，尝试刷新用户信息
      if (store.getters.token) {
        console.log('[App] 检测到用户已登录，强制刷新用户信息...');
        store.dispatch('getUserInfo', true)
          .then((userData) => {
            console.log('[App] 用户信息刷新成功:', userData);
            console.log('[App] 刷新后权限列表:', store.getters.permissions);
            
            // 再次检查权限并更新菜单可见性
            checkAndShowGraphMenu();
            
            // 如果有userData但菜单仍然不显示，强制显示
            if (userData && userData.permissions && 
              (userData.permissions.includes('graph:view') || userData.permissions.some(p => p.startsWith('analysis:')))) {
              console.log('[App] 从响应中检测到权限，强制显示菜单');
              showGraphMenu.value = true;
            }
          })
          .catch(error => {
            console.error('[App] 刷新用户信息失败:', error);
          });
      } else {
        console.log('[App] 用户未登录或无token');
      }
    });
    
    return {
      showHeader,
      hasPermission,
      hasAnyGraphPermission,
      hasAnyAnalysisPermission,
      graphMenuItem,
      showGraphMenu,
      isAdminUser,
      store,
      zhCn
    };
  }
};
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

#app {
  height: 100%;
  min-height: 100vh;
  overflow: hidden;
}

.el-container {
  height: 100%;
}

.el-aside {
  background-color: #304156;
  min-height: 100%;
  transition: width 0.3s;
}

.el-menu {
  border-right: none;
  background-color: transparent;
  width: 100%;
}

.el-menu-item {
  color: #bfcbd9;
}

.el-menu-item:hover {
  color: #409EFF;
}

.el-menu-item.is-active {
  color: #409EFF;
  background-color: #263445;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: none;
  height: calc(100vh - 60px);
}

.el-menu-vertical {
  height: 100%;
  width: 100%;
}

.loading-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}
</style>
